<template>
    <div>
        <el-card>
            <div>
                <el-form :model="form" ref="ruleForm" style="width: 100%">
                    <el-row :gutter="20">
                        <el-col :span="5">
                            <el-form-item label="项目名称">
                                <el-select
                                    style="width: 100%"
                                    placeholder="请选择项目"
                                    v-model="projectName"
                                    clearable
                                    @change="handleSelectProject"
                                >
                                    <el-option
                                        v-for="(project, idx) in projectList"
                                        :key="idx"
                                        :label="project.project_name_"
                                        :value="project"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="分项名称">
                                <el-select
                                    placeholder="请选择分项名称"
                                    @change="handleSelectShare"
                                    multiple
                                    v-model="selectShareList"
                                >
                                    <el-option
                                        v-for="(item ,idx) in shareList"
                                        :key="idx"
                                        :label="item.share_name_"
                                        :value="item"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="工种">
                                <el-select
                                    placeholder="请选择工种"
                                    @change="handleSelectTypeWork"
                                    multiple
                                    v-model="typeWorkList"
                                >
                                    <el-option
                                        v-for="(item ,idx) in workList"
                                        :key="idx"
                                        :label="item.user_or_type_work_"
                                        :value="item"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="责任人">
                                <el-select
                                    placeholder="请选择责任人"
                                    clearable
                                    @change="handleSelectUser"
                                    v-model="user"
                                >
                                    <el-option
                                        v-for="(item ,idx) in userList"
                                        :key="idx"
                                        :label="item.user_"
                                        :value="item"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-button type="primary" size="mini" @click="getData">查询</el-button>
                            <el-button size="mini" @click="getClear">重置</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </el-card>
        <el-card>
            <div class="btn-container">
                <div style="text-align: left">
                    <el-button
                        style="margin-left: 0"
                        :type="btnNotFinished"
                        @click="handleChangeFinishedType('NotFinished')"
                    >未完成</el-button>
                    <el-button
                        style="margin-left: 0"
                        :type="btnFinished"
                        @click="handleChangeFinishedType('Finished')"
                    >已完成</el-button>
                </div>
                <div>
                    <el-button class="btn-margin" :type="btnDay" @click="handleChangeType('Day')">日</el-button>
                    <el-button
                        class="btn-margin"
                        :type="btnWeek"
                        @click="handleChangeType('Week')"
                    >周</el-button>
                    <el-button
                        class="btn-margin"
                        :type="btnMonth"
                        @click="handleChangeType('Month')"
                    >月</el-button>
                </div>
            </div>
            <el-table :data="tableData" border>
                <el-table-column label="项目名称" prop="projectName" align="center"></el-table-column>
                <el-table-column label="分项名称" prop="shareName" align="center"></el-table-column>
                <el-table-column label="任务名称" prop="jobName" align="center"></el-table-column>
                <el-table-column label="计划开始时间" prop="startTime" align="center"></el-table-column>
                <el-table-column label="计划结束时间" prop="endTime" align="center"></el-table-column>
                <el-table-column label="上报流程状态" prop="bizStatus" align="center"></el-table-column>
                <el-table-column label="状态" prop="state" align="center"></el-table-column>
                <el-table-column label="角色/工种" prop="userOrTypeWork" align="center"></el-table-column>
                <el-table-column label="负责人" prop="user" align="center"></el-table-column>
                <el-table-column label="关联表单" prop="associatedForm" align="center">
                    <template #default="scope">
                        <el-button
                            type="text"
                            @click="handleForm(scope.$index, scope.row)"
                        >{{ scope.row.associatedForm }}</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <el-button type="text" @click="handleFeedBack(scope.$index, scope.row)">反馈</el-button>
                        <el-button type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" @click="handleDetail(scope.$index, scope.row)">详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </div>
</template>

<script>
export default {
    data() {
        return {
            account: '',
            tableData: [],
            projectId: '',
            projectNo: '',
            projectName: '',
            projectList: [],
            shareList: [],
            selectShareList: [],
            selectShare: '',
            selectShareId: '',
            jobDataList: [],
            typeWork: '',
            typeWorkList: [],
            user: '',
            btnNotFinished: 'info',
            btnFinished: '',
            btnDay: 'info',
            btnWeek: '',
            btnMonth: '',
            appKey: '',
        }
    },
    created() {
        this.account = localStorage.getItem('account')
        this.getProjectList()
        this.getPmAppKey()
    },
    methods: {
        // 根据登录信息查询PM免登录APPKEY
        getPmAppKey() {
            this.$axios.post(`/sys/ppcgLoiProject/getPmAppKey?account=123`).then(res => {
                if (res.isOk) {
                    sessionStorage.setItem('pmAppKey', res.data)
                    let pmAppData = JSON.parse(res.data)
                    this.appKey = pmAppData.appKey
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        // 查询项目列表
        getProjectList() {
            const param = { curPage: 1, pageSize: 10000, params: {} }
            this.$axios.post(`/form/formCustSql/view/list_ppcgSecondaryScheduleMst`, param).then(res => {
                if (res.isOk) {
                    this.projectList = res.data.list
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        // 选择项目
        handleSelectProject(item) {
            this.projectId = item.project_id_
            this.projectName = item.project_name_
            this.projectNo = item.project_no_
            this.selectShare = ''
            this.selectShareId = ''
            this.user = ''
            this.typeWork = ''
            this.getData()
            this.getShareListByMasterId(item.id_)
        },
        // 查询分项
        getShareListByMasterId(masterId) {
            const param = { curPage: 1, pageSize: 10000, params: { queryData: [{ name: "master_id_", con: "like", val: masterId }] } }
            this.$axios.post(`/form/formCustSql/view/list_ppcgSecondaryScheduleJobMst`, param).then(res => {
                if (res.isOk) {
                    this.shareList = res.data.list
                    this.getJobDataByMasterId(this.shareList.id_)
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        // 选择分项名称
        handleSelectShare(list) {
            let selectShare = '', selectShareId = '', ids = '', selectShareList = []
            list.map(d => {
                selectShare = (selectShare ? selectShare + ',' : '') + d.share_name_
                selectShareId = (selectShareId ? selectShareId + ',' : '') + d.share_id_
                ids = (ids ? ids + ',' : '') + d.id_
                selectShareList.push(d.share_name_)
            })
            this.selectShareList = selectShareList
            this.selectShare = selectShare
            this.selectShareId = selectShareId
            this.typeWork = ''
            this.getJobDataByMasterId(ids)
        },
        // 查询任务列表
        getJobDataByMasterId(masterId) {
            const param = { curPage: 1, pageSize: 10000, params: { queryData: [{ name: "master_id_", con: "in", val: masterId }] } }
            this.$axios.post(`/form/formCustSql/view/list_ppcgSecondaryScheduleJobDtl`, param).then(res => {
                if (res.isOk) {
                    this.jobDataList = res.data.list
                    let workList = [], userList = []
                    this.jobDataList.map(job => {
                        let isExist = false, isUserExist = false
                        // 工种去重
                        if (workList.length === 0) {
                            isExist = false
                        } else {
                            for (let d of workList) {
                                if (d.user_or_type_work_ === job.user_or_type_work_) {
                                    isExist = true
                                    break
                                }
                            }
                        }
                        if (!isExist && job.user_or_type_work_) {
                            workList.push({ user_or_type_work_: job.user_or_type_work_ })
                        }
                        this.workList = workList
                        // 责任人去重
                        if (userList.length === 0) {
                            isUserExist = false
                        } else {
                            for (let d of userList) {
                                if (d.user_ === job.user_) {
                                    isUserExist = true
                                    break
                                }
                            }
                        }
                        if (!isUserExist && job.user_) {
                            userList.push({ user_: job.user_ })
                        }
                        this.userList = userList
                    })
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        // 选择工种
        handleSelectTypeWork(list) {
            let typeWork = '', typeWorkList = []
            list.map(d => {
                typeWork = (typeWork ? typeWork + ',' : '') + d.user_or_type_work_
                typeWorkList.push(d.user_or_type_work_)
            })
            console.log('typeWorkList====>', typeWorkList)
            this.typeWorkList = typeWorkList
            this.typeWork = typeWork
            this.user = ''
        },
        // 选择责任人
        handleSelectUser(item) {
            this.user = item.user_
        },
        // 配置查询参数
        settingParam() {
            let startTime, endTime, state
            if (this.btnNotFinished === 'info') {
                state = '未完成'
            } else {
                state = '已完成'
            }
            if (this.btnDay === 'info') {
                startTime = this.$moment().format('YYYY-MM-DD')
                endTime = startTime
            } else if (this.btnWeek === 'info') {
                // 获取当前日期同一周第一天和最后一天
                startTime = this.$moment().isoWeekday(1).format('YYYY-MM-DD')
                endTime = this.$moment().isoWeekday(7).format('YYYY-MM-DD')
            } else if (this.btnMonth === 'info') {
                // 获取当前日期同一月第一天和最后一天
                startTime = this.$moment().startOf('month').format("YYYY-MM-DD")
                endTime = this.$moment().endOf('month').format("YYYY-MM-DD")
            }
            let param = `projectName=${this.projectName}&projectNo=${this.projectNo}&shareName=${this.selectShare}&shareId=${this.selectShareId}&userTypeName=${this.typeWork}&userName=${this.user}&startTime=${startTime}&endTime=${endTime}&state=${state}`
            return param
        },
        getData() {
            if (!this.projectNo) {
                this.$ElMessage({
                    message: '请选择项目',
                    type: 'error',
                })
                return
            }
            let param = this.settingParam()
            this.tableData = [] // 查询清空table
            this.$axios.post(`/sys/ppcgSecondaryScheduleMst/queryPpcgSecondaryScheduleList?${param}`).then(res => {
                if (res.isOk) {
                    this.tableData = res.data
                    this.tableData.map(d => {
                        this.getProgressData(d)
                        d.progressReportUrl = this.progressReportUrl
                    })
                    this.loginBpm()
                    this.total = res.total
                    this.$ElMessage({
                        message: '查询成功',
                        type: 'success',
                    })
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error'
                    })
                }
            })
        },
        // 查询是否已存在上报数据
        getProgressData(item) {
            let param = { curPage: 1, pageSize: 10, params: { queryData: [{ name: "project_no_", con: "=", val: this.projectNo }, { name: "sub_item_id", con: "=", val: item.shareId }, { name: "task_id", con: "=", val: item.id }] } }
            this.$axios.post(`/form/formCustSql/view/list_ppcgProgressReportTable`, param).then(res => {
                if (res.isOk) {
                    if (res.data.count > 0) {
                        console.log('已存在')
                        item.progressReportUrl = `http://pur.ppcg.com.cn/ppcgui/bpm/vueForm/instanceDetail.html?id=430454910722768897&account=${this.account}`
                        // window.open()
                    } else {
                        console.log('不存在')
                        item.progressReportUrl = `http://pur.ppcg.com.cn/ppcgui/bpm/vueForm/start.html?defId=430454540559974401&projectNo=${this.projectNo}&shareId=${item.shareId}&jobId=${item.id}&type=edit&account=${this.account}`
                        // window.open()
                    }
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error'
                    })
                }
            })
        },
        // 切换查询状态
        handleChangeFinishedType(type) {
            if (type === 'NotFinished') {
                this.btnNotFinished = 'info'
                this.btnFinished = ''
            } else {
                this.btnNotFinished = ''
                this.btnFinished = 'info'
            }
        },
        // 切换查询周期
        handleChangeType(type) {
            if (type === 'Day') {
                this.btnDay = 'info'
                this.btnWeek = ''
                this.btnMonth = ''
            } else if (type === 'Week') {
                this.btnDay = ''
                this.btnWeek = 'info'
                this.btnMonth = ''
            } else {
                this.btnDay = ''
                this.btnWeek = ''
                this.btnMonth = 'info'
            }
        },
        // 反馈点击跳转PM数据详情页面
        handleFeedBack(index, row) {
            window.open(row.progressReportUrl)
        },
        loginBpm() {
            this.$axios.post(`/org/login/valid_oa?account=${this.account}`).then(res => {
                if (res.isOk) {
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        // 关联表单调整跳转，点击跳转到PM数据列表页面，由mid决定调整列表
        handleForm(index, row) {
            window.open(`http://pm.ppcg.com.cn/menu.jsp?mid=402880e4732c417a01732d265c740037&appKey=${this.appKey}`)
        },
        handleEdit(index, row) {
            window.open(`http://pur.ppcg.com.cn/bpm/vueForm/start.html?instanceId=${'430454540559974401'}&instanceKey=jdsblc`)
        },
        handleDetail(index, row) {
            window.open(`http://pur.ppcg.com.cn/ppcgui/bpm/vueForm/instanceDetail.html?id=430454910722768897`)
        },
        // 重置
        getClear() {
            this.projectId = ''
            this.projectNo = ''
            this.projectName = ''
            this.selectShare = ''
            this.selectShareId = ''
            this.user = ''
            this.typeWork = ''
        },
    }
}
</script>

<style scoped>
.el-tabs__content {
    padding: 0 !important;
}
.btn-margin {
    margin-left: 0;
}
.btn-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 1rem;
}
</style>